# -*- encoding: utf-8 -*-
import time
import wizard
import netsvc
import pooler
from osv import fields, osv
from tools.translate import _
from osv.orm import browse_record, browse_null
import datetime


def _aas_academic_plan_line_current_year(self, cr, uid, data, context):
	pool = pooler.get_pool(cr.dbname)
	if not context:
		context = {}
	academic_plan_obj = pool.get('aas.academic.plan')
	academic_plan_line_obj = pool.get('aas.academic.plan.line')
	year_obj = pool.get('aas.academic.year')
	year_id = False
	current_academic_state = year_obj.get_current_academic_state(cr, uid, context=context)
	if current_academic_state[0]:
		year_id = current_academic_state[0].id
	plan_line_ids = []
	if year_id:
		current_academic_plan = academic_plan_obj.search(cr, uid, [('academic_year', '=', year_id)], context=context)
		if len(current_academic_plan):
			plan_line_ids = academic_plan_line_obj.search(cr, uid, [('academic_plan', 'in', current_academic_plan)])
	result = {
        'domain': "[('id', 'in', " + str(plan_line_ids) + ")]",
        'name': 'Academic Plan Lines',
        'view_type': 'form',
        'view_mode': 'tree,form',
	    'src_model': 'aas.academic.plan.line',
        'res_model': 'aas.academic.plan.line',
        'view_id': False,
        'type': 'ir.actions.act_window'
	}
	return result


class wizard_aas_academic_plan_line_current_year(wizard.interface):
	states = {
		'init': {
			'actions': [],
			'result': {'type': 'action', 'action': _aas_academic_plan_line_current_year, 'state': 'end'}
		}
	}	
wizard_aas_academic_plan_line_current_year("aas.academic.plan.line.current.year")





class aas_academic_semester_auto_generating_week_wizard(wizard.interface):
	
	_form = '''
		<form string="Generate Academic Weeks">
			<field name="semester"/>
			<newline/>
			<field name="date_from"/>
			<field name="prefix"/>
			<newline/>
			<field name="from_no" colspan="2"/>
			<field name="to_no" colspan="2"/>
	    </form>
	'''
	
	_fields = {
		'semester': {'type': 'many2one', 'relation': 'aas.academic.semester', 'readonly': True, 'string': 'Generate For Semester'},
	    'prefix': {'type': 'char', 'size': 64, 'string': 'Prefix'},
	    'from_no': {'type': 'integer', 'required': True, 'string': 'From Number'},
	    'to_no': {'type': 'integer', 'required': True, 'string': 'To Number'},
	    'date_from': {'type': 'date', 'required': True, 'string': 'From Date'},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if data.has_key('id'):
			res['semester'] = data['id']
		return res
    
	def _generate_academic_weeks(self, cr, uid, data, context):
		if data.has_key('form') and data.has_key('id'):
			pool = pooler.get_pool(cr.dbname)
			
			week_obj = pool.get('aas.academic.week')
			semester_obj = pool.get('aas.academic.semester')
			year_obj = pool.get('aas.academic.year')
			
			semester_id = data['id']
			prefix = data['form'].get('prefix', '')
			from_no = data['form'].get('from_no', 0)
			to_no = data['form'].get('to_no', -1)
			date_from = data['form'].get('date_from', False)
			date_from_obj = datetime.datetime.strptime(date_from, '%Y-%m-%d').date()
			week_delta = datetime.timedelta(weeks = 1)
			days_delta = datetime.timedelta(days = 6)
			
			if date_from_obj.weekday() != 0:
				raise osv.except_osv(_('Error!'), _('"From Date" must be on Monday!')) 
			
			i = from_no
			date_start = date_from_obj
			date_end = date_start + days_delta
			
			while i <= to_no:
				week_name = ''
				if prefix:
					prefix = prefix.strip()
					week_name += prefix + ' '
				week_name += str(i)
				week_data = {
					'name': week_name, 
					'number': i, 
					'academic_semester': semester_id,
					'date_start': date_start.strftime('%Y-%m-%d'),
					'date_end': date_end.strftime('%Y-%m-%d'),
				}
				
#				try:
				week = week_obj.create(cr, uid, week_data, context=context)
#				except:
#					raise osv.except_osv(_('Error!'), _('Cannot create weeks in this period! Maybe the name already exists!'))
				i += 1
				date_start += week_delta
				date_end = date_start + days_delta
			
			semester = semester_obj.browse(cr, uid, semester_id, context=context)
			if len(semester.academic_weeks):
				sql = '''
					SELECT MIN(date_start), MAX(date_end)
					FROM aas_academic_week
					WHERE academic_semester = %s
				'''
				cr.execute(sql, (semester_id,))
				if cr.rowcount > 0:
					(min_date_start, max_date_end) = cr.fetchone()
					semester_obj.write(cr, uid, [semester.id], {'date_start': min_date_start, 'date_end': max_date_end}, context=context)
			
			if semester.academic_year.id:
				year = year_obj.browse(cr, uid, semester.academic_year.id, context=context)
				if len(year.academic_semesters):
					sql = '''
						SELECT MIN(date_start), MAX(date_end)
						FROM aas_academic_semester
						WHERE academic_year = %s
					'''
					cr.execute(sql, (year.id,))
					if cr.rowcount > 0:
						(min_date_start, max_date_end) = cr.fetchone()
						year_obj.write(cr, uid, [year.id], {'date_start': min_date_start, 'date_end': max_date_end}, context=context)
						
		return {}
	
	def _show_semester(self, cr, uid, data, context={}):
	    value = {
            'view_type': 'form', 
            'view_mode': 'form,tree', 
            'res_model': data['model'],
            'res_id': data['id'],
            'type': 'ir.actions.act_window', 
            'target': 'current',
        }
	    return value
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('end', 'Cancel', 'gtk-cancel', True),
																				   ('generate', 'Generate', 'gtk-ok', True),]},
		},
		'generate': {
			'actions': [_generate_academic_weeks],
			'result': {'type': 'state', 'state': 'done'},
		},
		'done': {
            'actions': [],
            'result': {'type': 'action', 'action': _show_semester, 'state': 'end'},
        },
	}	
aas_academic_semester_auto_generating_week_wizard("aas.academic.semester.auto.generating.week")



class aas_academic_plan_auto_generating_plan_line_wizard(wizard.interface):
	
	_form = '''
		<form string="Generate Academic Plan Lines">
			<field name="academic_plan"/>
			<field name="academic_week_state"/>
			<newline/>
			<field name="academic_sessions" colspan="4" nolabel="1"/>
			<newline/>
			<field name="academic_weeks" colspan="4" nolabel="1"/>
	    </form>
	'''
	
	_fields = {
		'academic_plan': {'type': 'many2one', 'relation': 'aas.academic.plan', 'readonly': True, 'string': 'Generate For Plan'},
		'academic_week_state': {'type': 'many2one', 'relation': 'aas.academic.week.state', 'string': 'Academic Week State', 'required': True},
		'academic_sessions': {'type': 'many2many', 'relation': 'aas.academic.session', 'string': 'Academic Sessions'},
		'academic_weeks': {'type': 'many2many', 'relation': 'aas.academic.week', 'string': 'Academic Weeks'},
	}
	
	def _init(self, cr, uid, data, context):
		res = {}
		if data.has_key('id'):
			res['academic_plan'] = data['id']
		return res
    
	def _generate_academic_plan_lines(self, cr, uid, data, context):
		if data.has_key('form') and data.has_key('id'):
			pool = pooler.get_pool(cr.dbname)
			
			week_obj = pool.get('aas.academic.week')
			plan_obj = pool.get('aas.academic.plan')
			plan_line_obj = pool.get('aas.academic.plan.line')
			
			plan_id = data['id']
			week_state_id = data['form'].get('academic_week_state', '')
			sessions_ids = data['form'].get('academic_sessions', [])
			weeks_ids = data['form'].get('academic_weeks', [])
			
			if sessions_ids:
				sessions_ids = sessions_ids[0][2]
			if weeks_ids:
				weeks_ids = weeks_ids[0][2]
				
			for week_id in weeks_ids:
				for session_id in sessions_ids:
					plan_line_data = {
						'academic_plan': plan_id,
        				'academic_session': session_id,
        	   			'academic_week': week_id,
        	      		'academic_week_state': week_state_id,
					}
					plan_line_obj.create(cr, uid, plan_line_data, context=context)
					
		return {}
	
	def _show_plan(self, cr, uid, data, context={}):
	    value = {
            'view_type': 'form', 
            'view_mode': 'form,tree', 
            'res_model': data['model'],
            'res_id': data['id'],
            'type': 'ir.actions.act_window', 
            'target': 'current',
        }
	    return value
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': [('end', 'Cancel', 'gtk-cancel', True),
																				   ('generate', 'Generate', 'gtk-ok', True),]},
		},
		'generate': {
			'actions': [_generate_academic_plan_lines],
			'result': {'type': 'state', 'state': 'done'},
		},
		'done': {
            'actions': [],
            'result': {'type': 'action', 'action': _show_plan, 'state': 'end'},
        },
	}	
aas_academic_plan_auto_generating_plan_line_wizard("aas.academic.plan.auto.generating.plan.line")



class aas_show_current_academic_state_wizard(wizard.interface):
	
	_readonly_str = ' readonly="True"'
	_required_str = '' 
	
	_form_template = '''
		<form string="%s">
			<group colspan="4" col="6">
				<field name="year" colspan="2"%s%s/>
				<field name="semester" colspan="2"%s%s/>
				<field name="week" colspan="2"%s%s/>
			</group>
	    </form>
	'''
	
	_form = _form_template % (_('Current Academic State'),
								_readonly_str, _required_str, 
								_readonly_str, _required_str,
								_readonly_str, _required_str,)
	
	_fields = {
		'year': {'type': 'many2one', 'relation': 'aas.academic.year', 'string': _('Year')},
		'semester': {'type': 'many2one', 'relation': 'aas.academic.semester', 'string': _('Semester')},
		'week': {'type': 'many2one', 'relation': 'aas.academic.week', 'string': _('Week')},
	}
	
	def _init(self, cr, uid, data, context):
		res = {'year': False, 'semester': False, 'week': False}
		pool = pooler.get_pool(cr.dbname)
		year_obj = pool.get('aas.academic.year')
		(year, semester, week) = year_obj.get_current_academic_state(cr, uid, context=context)
		if year: res['year'] = year.id
		if semester: res['semester'] = semester.id
		if week: res['week'] = week.id
		return res
   
	states = {
		'init': {
			'actions': [_init],
			'result': {'type': 'form', 'arch': _form, 'fields': _fields, 'state': []},
		},
	}	
aas_show_current_academic_state_wizard("aas.show.current.academic.state")

class aas_edit_current_academic_state_wizard(aas_show_current_academic_state_wizard):
	_readonly_str = ''
	_required_str = ' required="True"'
	 
	_form = aas_show_current_academic_state_wizard._form_template % (_('Current Academic State'),
																	_readonly_str, _required_str,
																	_readonly_str, _required_str,
																	_readonly_str, _required_str,)
	
	def _set_current_academic_state(self, cr, uid, data, context):
		pool = pooler.get_pool(cr.dbname)
		year_obj = pool.get('aas.academic.year')
		form = data['form']
		year_id = form.get('year', -1)
		semester_id = form.get('semester', -1)
		week_id = form.get('week', -1)
		year_obj.set_current_academic_state(cr, uid, year_id, semester_id, week_id, context=context)
		return {}
	
	states = {
		'init': {
			'actions': [aas_show_current_academic_state_wizard._init],
			'result': {'type': 'form', 'arch': _form, 'fields': aas_show_current_academic_state_wizard._fields, 'state': [('set', _('Set'), 'gtk-ok', True),]},
		},
		'set': {
			'actions': [_set_current_academic_state],
			'result': {'type': 'state', 'state': 'init'},
		},
	}	
aas_edit_current_academic_state_wizard("aas.edit.current.academic.state")